import { NextRequest, NextResponse } from 'next/server';
import { IndependentTablesDatabase } from '../../../lib/independent-tables-database';
import { verifyDeletePermission } from '@/lib/auth-middleware';

// 创建数据库实例
let db: IndependentTablesDatabase;

function getDatabase() {
  if (!db) {
    db = new IndependentTablesDatabase();
  }
  return db;
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const deviceId = searchParams.get('deviceId');
    const parameterType = searchParams.get('type'); // 'naming', 'position', 'base'

    if (!deviceId) {
      return NextResponse.json({ error: '缺少设备ID参数' }, { status: 400 });
    }

    const deviceIdNum = parseInt(deviceId);
    if (isNaN(deviceIdNum)) {
      return NextResponse.json({ error: '设备ID必须是数字' }, { status: 400 });
    }

    // 检查设备是否存在
    const database = getDatabase();
    const device = database.getDeviceById(deviceIdNum);
    if (!device) {
      return NextResponse.json({ error: '设备不存在' }, { status: 404 });
    }

    let parameters;
    
    if (parameterType) {
      // 获取特定类型的参数
      switch (parameterType) {
        case 'naming':
          parameters = db.getDeviceNamingParameters(deviceIdNum);
          break;
        case 'position':
          parameters = db.getDevicePositionParameters(deviceIdNum);
          break;
        case 'base':
          parameters = db.getDeviceBaseParameters(deviceIdNum);
          break;
        default:
          return NextResponse.json({ error: '无效的参数类型' }, { status: 400 });
      }
    } else {
      // 获取所有类型的参数
      parameters = {
        naming: db.getDeviceNamingParameters(deviceIdNum),
        position: db.getDevicePositionParameters(deviceIdNum),
        base: db.getDeviceBaseParameters(deviceIdNum)
      };
    }

    return NextResponse.json({
      success: true,
      device: device,
      parameters: parameters,
      tableNames: db.getDeviceTableNames(deviceIdNum)
    });

  } catch (error) {
    console.error('获取设备参数失败:', error);
    return NextResponse.json(
      { error: '获取设备参数失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { deviceId, parameterType, parameters } = body;

    if (!deviceId || !parameterType || !parameters) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
    }

    const deviceIdNum = parseInt(deviceId);
    if (isNaN(deviceIdNum)) {
      return NextResponse.json({ error: '设备ID必须是数字' }, { status: 400 });
    }

    // 检查设备是否存在
    const device = db.getDeviceById(deviceIdNum);
    if (!device) {
      return NextResponse.json({ error: '设备不存在' }, { status: 404 });
    }

    const insertedParameters = [];

    // 根据参数类型插入数据
    for (const param of parameters) {
      let insertedParam;
      
      switch (parameterType) {
        case 'naming':
          insertedParam = db.insertNamingParameter(deviceIdNum, param);
          break;
        case 'position':
          insertedParam = db.insertPositionParameter(deviceIdNum, param);
          break;
        case 'base':
          insertedParam = db.insertBaseParameter(deviceIdNum, param);
          break;
        default:
          return NextResponse.json({ error: '无效的参数类型' }, { status: 400 });
      }
      
      insertedParameters.push(insertedParam);
    }

    return NextResponse.json({
      success: true,
      message: `成功插入 ${insertedParameters.length} 个${parameterType}参数`,
      parameters: insertedParameters
    });

  } catch (error) {
    console.error('插入设备参数失败:', error);
    return NextResponse.json(
      { error: '插入设备参数失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { deviceId, parameterType, parameterId, parameter } = body;

    if (!deviceId || !parameterType || !parameterId || !parameter) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
    }

    const deviceIdNum = parseInt(deviceId);
    const parameterIdNum = parseInt(parameterId);
    
    if (isNaN(deviceIdNum) || isNaN(parameterIdNum)) {
      return NextResponse.json({ error: 'ID必须是数字' }, { status: 400 });
    }

    // 检查设备是否存在
    const device = db.getDeviceById(deviceIdNum);
    if (!device) {
      return NextResponse.json({ error: '设备不存在' }, { status: 404 });
    }

    // 获取表名
    const tableNames = db.getDeviceTableNames(deviceIdNum);
    let tableName;
    
    switch (parameterType) {
      case 'naming':
        tableName = tableNames.naming;
        break;
      case 'position':
        tableName = tableNames.position;
        break;
      case 'base':
        tableName = tableNames.base;
        break;
      default:
        return NextResponse.json({ error: '无效的参数类型' }, { status: 400 });
    }

    // 构建更新SQL
    const updateFields = [];
    const updateValues = [];
    
    if (parameter.parameter_name !== undefined) {
      updateFields.push('parameter_name = ?');
      updateValues.push(parameter.parameter_name);
    }
    if (parameter.parameter_value !== undefined) {
      updateFields.push('parameter_value = ?');
      updateValues.push(parameter.parameter_value);
    }
    if (parameter.data_type !== undefined) {
      updateFields.push('data_type = ?');
      updateValues.push(parameter.data_type);
    }
    if (parameter.measurement_unit !== undefined) {
      updateFields.push('measurement_unit = ?');
      updateValues.push(parameter.measurement_unit);
    }
    if (parameter.is_required !== undefined) {
      updateFields.push('is_required = ?');
      updateValues.push(parameter.is_required ? 1 : 0);
    }
    if (parameter.data_source !== undefined) {
      updateFields.push('data_source = ?');
      updateValues.push(parameter.data_source);
    }
    
    updateFields.push('updated_at = ?');
    updateValues.push(new Date().toISOString());
    updateValues.push(parameterIdNum);

    // 执行更新
    const updateSql = `UPDATE ${tableName} SET ${updateFields.join(', ')} WHERE id = ?`;
    const stmt = (db as any).db.prepare(updateSql);
    const result = stmt.run(...updateValues);

    if (result.changes === 0) {
      return NextResponse.json({ error: '参数不存在或更新失败' }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      message: '参数更新成功',
      changes: result.changes
    });

  } catch (error) {
    console.error('更新设备参数失败:', error);
    return NextResponse.json(
      { error: '更新设备参数失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // Verify authentication and delete permissions
    const authResult = await verifyDeletePermission();
    if (!authResult.success) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    if (!authResult.canDelete) {
      return NextResponse.json({
        success: false,
        error: '权限不足：无法删除设备参数'
      }, { status: 403 });
    }

    const { searchParams } = new URL(request.url);
    const deviceId = searchParams.get('deviceId');
    const parameterType = searchParams.get('type');
    const parameterId = searchParams.get('parameterId');

    if (!deviceId || !parameterType || !parameterId) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
    }

    const deviceIdNum = parseInt(deviceId);
    const parameterIdNum = parseInt(parameterId);
    
    if (isNaN(deviceIdNum) || isNaN(parameterIdNum)) {
      return NextResponse.json({ error: 'ID必须是数字' }, { status: 400 });
    }

    // 检查设备是否存在
    const device = db.getDeviceById(deviceIdNum);
    if (!device) {
      return NextResponse.json({ error: '设备不存在' }, { status: 404 });
    }

    // 获取表名
    const tableNames = db.getDeviceTableNames(deviceIdNum);
    let tableName;
    
    switch (parameterType) {
      case 'naming':
        tableName = tableNames.naming;
        break;
      case 'position':
        tableName = tableNames.position;
        break;
      case 'base':
        tableName = tableNames.base;
        break;
      default:
        return NextResponse.json({ error: '无效的参数类型' }, { status: 400 });
    }

    // 执行删除
    const deleteSql = `DELETE FROM ${tableName} WHERE id = ?`;
    const stmt = (db as any).db.prepare(deleteSql);
    const result = stmt.run(parameterIdNum);

    if (result.changes === 0) {
      return NextResponse.json({ error: '参数不存在或删除失败' }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      message: '参数删除成功',
      changes: result.changes
    });

  } catch (error) {
    console.error('删除设备参数失败:', error);
    return NextResponse.json(
      { error: '删除设备参数失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}
